#include "LoginDlg.h"

#include <QGridLayout>
#include <QFormLayout>
#include <QLabel>
#include <QComboBox>
#include <QLineEdit>
#include <QPushButton>
#include "Login.h"
#include <QFile>
#include "VisionMainWnd.h"


LoginDlg::LoginDlg(QWidget* parent)
{
	initLayout();
	setParent(parent);	
	setWindowFlags(Qt::Dialog);
}

void LoginDlg::initLayout()
{
	resize(250, 150);

	QLabel* userLbl = new QLabel("用户：");
	account_ = new QComboBox();
	account_->addItem("操作员");
	account_->addItem("管理员");
	account_->addItem("超级用户");
	account_->setCurrentIndex(0);
	QLabel* pwLbl = new QLabel("密码");
	passwordEdit_ = new QLineEdit;
	passwordEdit_->setEchoMode(QLineEdit::Password);

	QPushButton* btnLogin = new QPushButton("登录");

	QGridLayout* loginLyt = new QGridLayout();
	
	
	int row = 0;
	loginLyt->addItem(new QSpacerItem(100, 20, QSizePolicy::Fixed, QSizePolicy::Expanding), row, 0,1,7,Qt::AlignCenter);
	row++;
	loginLyt->addWidget(userLbl, row, 1, 1, 1);
	loginLyt->addWidget(account_, row, 2, 1, 3);

	row++;
	loginLyt->addWidget(pwLbl, row, 1, 1, 1);
	loginLyt->addWidget(passwordEdit_, row, 2, 1, 3);

	row++;
	loginLyt->addItem(new QSpacerItem(100, 10, QSizePolicy::Fixed, QSizePolicy::Expanding), row, 0, 1, 7, Qt::AlignCenter);

	row++;
	loginLyt->addWidget(btnLogin, row, 3, 1, 2);

	row++;
	loginLyt->addItem(new QSpacerItem(100, 20, QSizePolicy::Fixed, QSizePolicy::Expanding), row, 0, 1, 7, Qt::AlignCenter);

	setLayout(loginLyt);

	connect(btnLogin, SIGNAL(clicked(bool)), this, SLOT(on_login()));
}

void LoginDlg::on_login()
{
	int user = account_->currentIndex();
	QString pw = passwordEdit_->text();
	bool passwordSuc = false;
	QString loginInfo;
	switch (user)
	{
	case UserType::superUser:
		passwordSuc = pw == "visionrobot" ? true : false;
		loginInfo = "SuperUser login success.";
		break;
	case UserType::administrator:
		passwordSuc = pw == "123456" ? true : false;
		loginInfo = "Administrator login success.";
		break;
	case UserType::user:
		passwordSuc = true;
		loginInfo = "User login success.";
		break;
	default:
		break;
	}
	if (passwordSuc)
	{
		Login::instance()->setUsr((UserType)user);
		qInfo() << loginInfo;
		VisionMainWnd* m = (VisionMainWnd*)parent();
		m->updateUIByUser();
			
		close();
	}
}
